<?php

use Illuminate\Database\Capsule\Manager as DB;
use \app\modules\Merchant\models\goodsModel;
#[代理商管理]
class AgentController extends McommonController
{

    public function init()
    {
        parent::init();
        $this->model      = (new memberModel)->where('level', '>', 0);
        $this->table      = 'member';
        $this->primaryKey = 'id';

    }

    #[代理商品]
    public function goodsAction()
    {
        if ($this->isPost()) {
            $query    = goodsModel::query();
            $query    = $query->leftJoin('agent_goods', 'goods.id', '=', 'agent_goods.goods_id')->where('goods.dianpu_id', $this->auth->dianpu_id);
            $keywords = $this->get('keywords');
            if (!empty($keywords)) {
                array_push($this->search, ['goods.id', '=', $keywords]);
                array_push($this->search, ['goods.title', 'like', "%{$keywords}%", 'or']);
            }
            $minprice = $this->get('minprice', 0);
            if(!empty($minprice)){
                array_push($this->search, ['goods.price', '>=', $minprice]);
            }
            $maxprice = $this->get('maxprice', 0);
            if(!empty($maxprice)){
                array_push($this->search, ['goods.price', '<=', $maxprice]);
            }
            if (!empty($this->search)) {
                $query = $query->where(function ($query) {
                    foreach ($this->search as $v) {
                        if (isset($v[3]) && strtolower($v[3]) == 'or') {
                            $query = $query->orWhere([$v]);
                        } else {
                            $query = $query->where([$v]);
                        }
                    }
                });
            }

            $total = $query->count();
            $sort  = $this->get('sort', 'sortorder');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page  = $this->get('page');

            if (!empty($page)) {
                $limit  = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query  = $query->offset($offset)->limit($limit);
            }
            $rows = $query->get();

            json(['total' => $total, 'rows' => $rows]);
        } else {
            $this->_view->display('agent/goods.html');
        }
    }

    #[设置分红]
    public function bonusAction()
    {
        if ($this->isPost()) {
            $rows = $this->postData;
            $event = 'edit';
            $current_agentgoods = agentgoodsModel::query()->where('goods_id', $rows['goods_id'])->first();
            if($current_agentgoods){
                if($current_agentgoods->status == 1 && $rows['status'] == 0){
                    $event = 'del';
                }
                if($current_agentgoods->status == 0 && $rows['status'] == 1){
                    $event = 'add';
                }
            }else{
                $event = 'add';
            }
            $rows['gd_status'] = 0;
            $rows['gd_self_rules'] = 0;
            $rows['gd_rules'] = '';
            $rows['qd_status'] = 0;
            $rows['qd_self_rules'] = 0;
            $rows['qd_rules'] = '';
            $dianpu_commission_permission = \app\modules\Admin\models\dianpuModel::query()->where('id', $this->auth->dianpu_id)->value('commission_permission');
            $defaultRules = \dianpuModel::getCommissionPermission();
            foreach ($defaultRules as $key=>$item){
                if($key === 'jichafenhong'){
                    if(($dianpu_commission_permission & $item['permission']) !== $item['permission']){
                        $rows['jc_status'] = 0;
                        $rows['jc_self_rules'] = 0;
                        $rows['jc_rules'] = '';
                    }
                }elseif ($key === 'pingjifenhong'){
                    if(($dianpu_commission_permission & $item['permission']) !== $item['permission']){
                        $rows['pj_status'] = 0;
                        $rows['pj_self_rules'] = 0;
                        $rows['pj_level1_rules'] = '';
                        $rows['pj_level2_rules'] = '';
                    }
                }elseif ($key === 'tuikefenhong'){
                    if(($dianpu_commission_permission & $item['permission']) !== $item['permission']){
                        $rows['tk_status'] = 0;
                        $rows['tk_self_rules'] = 0;
                        $rows['tk_zhitui_rules'] = '';
                        $rows['tk_jiantui_rules'] = '';
                    }
                }
            }
            agentgoodsModel::updateOrInsert(
                ['goods_id' => $rows['goods_id']],
                $rows
            );
            \app\modules\Admin\service\Agentgoodslog::addLog([
                'goods_id' => $rows['goods_id'],
                'event' => $event,
                'oper_type' => 'user',
                'oper_id' => $this->auth->member_id
            ]);
            ret(0, '代理商品分红设置成功');
        } else {
            $id = $this->get('id');
            $this->_view->assign('goodsDetail', goodsModel::find($id)->toJson());
            $levelList       = agentlevelModel::get();
            $tuikeLevelList  = tuikelevelModel::get();
            if (agentgoodsModel::where('goods_id', $id)->exists()) {
                $agentGoods = agentgoodsModel::find($id);
                $this->_view->assign('params', $agentGoods->toJson());
                if (!$agentGoods->jc_rules || !$agentGoods->pj_level1_rules || !$agentGoods->pj_level2_rules) {
                    $jc_rules = [];
                    foreach ($levelList as $oneLevel) {
                        array_push($jc_rules, [
                            'level' => $oneLevel->level,
                            'money' => '',
                            'ratio' => '',
                        ]);
                    }
                }
                $this->_view->assign('commission_rules', $agentGoods->jc_rules ?: json_encode($jc_rules));
                $this->_view->assign('pj_level1_rules', $agentGoods->pj_level1_rules ?: json_encode($jc_rules));
                $this->_view->assign('pj_level2_rules', $agentGoods->pj_level2_rules ?: json_encode($jc_rules));
                if (!$agentGoods->tk_rules) {
                    $tk_rules = [];
                    foreach ($tuikeLevelList as $oneLevel) {
                        array_push($tk_rules, [
                            'level' => $oneLevel->level,
                            'money' => '',
                            'ratio' => '',
                        ]);
                    }
                }
                $this->_view->assign('tuike_zhitui_rules', $agentGoods->tk_zhitui_rules ?: json_encode($tk_rules));
                $this->_view->assign('tuike_jiantui_rules', $agentGoods->tk_jiantui_rules ?: json_encode($tk_rules));
            } else {
                $agent_goods             = $this->getTableColumn('agent_goods');
                $agent_goods['goods_id'] = $id;
                $this->_view->assign('params', json_encode($agent_goods));
                $jc_rules = [];
                foreach ($levelList as $oneLevel) {
                    array_push($jc_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('commission_rules', json_encode($jc_rules));
                $this->_view->assign('pj_level1_rules', json_encode($jc_rules));
                $this->_view->assign('pj_level2_rules', json_encode($jc_rules));
                $tk_rules = [];
                foreach ($tuikeLevelList as $oneLevel) {
                    array_push($tk_rules, [
                        'level' => $oneLevel->level,
                        'money' => '',
                        'ratio' => '',
                    ]);
                }
                $this->_view->assign('tuike_zhitui_rules', json_encode($tk_rules));
                $this->_view->assign('tuike_jiantui_rules', json_encode($tk_rules));
            }
            $dianpu_commission_permission = \app\modules\Admin\models\dianpuModel::query()->where('id', $this->auth->dianpu_id)->value('commission_permission');
            $defaultRules = \dianpuModel::getCommissionPermission();
            $dianpuRules = [
                'jichafenhong' => 0,
                'pingjifenhong' => 0,
                'tuikefenhong' => 0
            ];
            foreach ($defaultRules as $key=>$item){
                if($key === 'jichafenhong'){
                    if(($dianpu_commission_permission & $item['permission']) === $item['permission']){
                        $dianpuRules['jichafenhong'] = 1;
                    }
                }elseif ($key === 'pingjifenhong'){
                    if(($dianpu_commission_permission & $item['permission']) === $item['permission']){
                        $dianpuRules['pingjifenhong'] = 1;
                    }
                }elseif ($key === 'tuikefenhong'){
                    if(($dianpu_commission_permission & $item['permission']) === $item['permission']){
                        $dianpuRules['tuikefenhong'] = 1;
                    }
                }
            }
            $this->_view->assign('levelList', $levelList->toJson());
            $this->_view->assign('tuikeLevelList', $tuikeLevelList->toJson());
            $this->_view->assign('dianpuRules', json_encode($dianpuRules, JSON_UNESCAPED_UNICODE));
            $this->_view->display('agent/bonus.html');
        }
    }

    #[参与分红]
    public function bepartakeAction()
    {
        $rows = $this->postData;
        if ($rows['id'] && $rows['id']>0){
            $this->doBepartake($rows['id']);
        }elseif($rows['ids'] && !empty($rows['ids'])){
            foreach ($rows['ids'] as $id){
                $this->doBepartake($id);
            }
        }
        ret(0, '商品参与分红设置成功');
    }

    private function doBepartake($id)
    {
        $event = 'add';
        $add_log = 1;
        $current_agentgoods = agentgoodsModel::query()->where('goods_id', $id)->first();
        if ($current_agentgoods) {
            if($current_agentgoods->status == 1){
                $add_log = 0;
            }
            agentgoodsModel::where('goods_id', $id)->update(['status' => 1]);
        } else {
            $dianpu_commission_permission = \app\modules\Admin\models\dianpuModel::query()->where('id', $this->auth->dianpu_id)->value('commission_permission');
            $defaultRules = \dianpuModel::getCommissionPermission();
            $agentGoods = $this->getTableColumn((new agentgoodsModel())->getTable());
            $agentGoods['goods_id'] = $id;
            $agentGoods['status'] = 1;
            $agentGoods['jc_status'] = 0;
            $agentGoods['tk_status'] = 0;
            $agentGoods['pj_status'] = 0;
            $agentGoods['gd_status'] = 0;
            $agentGoods['qd_status'] = 0;
            foreach ($defaultRules as $key=>$item){
                if($key === 'jichafenhong'){
                    if(($dianpu_commission_permission & $item['permission']) === $item['permission']){
                        $agentGoods['jc_status'] = 1;
                    }
                }elseif ($key === 'pingjifenhong'){
                    if(($dianpu_commission_permission & $item['permission']) === $item['permission']){
                        $agentGoods['pj_status'] = 1;
                    }
                }elseif ($key === 'tuikefenhong'){
                    if(($dianpu_commission_permission & $item['permission']) === $item['permission']){
                        $agentGoods['tk_status'] = 1;
                    }
                }
            }
            agentgoodsModel::insert($agentGoods);
        }
        if($add_log){
            \app\modules\Admin\service\Agentgoodslog::addLog([
                'goods_id' => $id,
                'event' => $event,
                'oper_type' => 'user',
                'oper_id' => $this->auth->member_id
            ]);
        }
    }

    #[不参与分红]
    public function nopartakeAction()
    {
        $rows = $this->postData;
        if ($rows['id'] && $rows['id']>0){
            $this->donopartake($rows['id']);
        }elseif($rows['ids'] && !empty($rows['ids'])){
            foreach ($rows['ids'] as $id){
                $this->donopartake($id);
            }
        }
        ret(0, '商品不参与分红设置成功');
    }

    private function donopartake($id)
    {
        $event = 'del';
        $add_log = 0;
        $current_agentgoods = agentgoodsModel::query()->where('goods_id', $id)->first();
        if ($current_agentgoods) {
            $add_log = 1;
            if($current_agentgoods->status == 0){
                $add_log = 0;
            }
        }
        agentgoodsModel::where('goods_id', $id)->update(['status' => 0]);
        if($add_log){
            \app\modules\Admin\service\Agentgoodslog::addLog([
                'goods_id' => $id,
                'event' => $event,
                'oper_type' => 'user',
                'oper_id' => $this->auth->member_id
            ]);
        }
    }


    #[代理佣金记录]
    public function rewardAction()
    {
        if ($this->isPost()) {
            $params   = $this->postData;
            $page     = $params['page'] ?? 1;
            $per_page = $params['rows'] ?? 10;
            $rewardModel = (new agentrewardModel())->newQuery();
            $query       = $rewardModel->with(['agent', 'buyer', 'order'=>function($withOrderQuery){
                $withOrderQuery->where('dianpu_id', $this->auth->dianpu_id);
            }, 'orderItem'])->whereHas('order', function ($withOrderQuery){
                $withOrderQuery->where('dianpu_id', $this->auth->dianpu_id);
            })->orderByDesc('created_at');
            if (isset($params['mode']) && $params['mode'] != 'all') {
                switch ($params['mode']) {
                    case 'waiting':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_WAITING);
                        break;
                    case 'accounted':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_ACCOUNTED);
                        break;
                    case 'cancel':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_CANCEL);
                        break;
                    case 'back':
                        $query = $query->where('status', agentrewardModel::COMMISSION_REWARD_STATUS_BACK);
                        break;
                }
            }
            if (isset($params['start_on']) && !empty($params['start_on'])) {
                $query = $query->whereDate('created_at', '>=', $params['start_on']);
            }
            if (isset($params['end_on']) && !empty($params['end_on'])) {
                $query = $query->whereDate('created_at', '<=', $params['end_on']);
            }
            if (isset($params['keywords']) && !empty($params['keywords'])) {
                if (isset($params['keywordsType']) && !empty($params['keywordsType'])) {
                    switch ($params['keywordsType']) {
                        case 'agent_id':
                            $query = $query->where('agent_id', $params['keywords']);
                            break;
                        case 'agent_phone':
                            $agent_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                            $query    = $query->where('agent_id', $agent_id);
                            break;
                        case 'order_id':
                            $query = $query->where('order_id', $params['keywords']);
                            break;
                        case 'order_sn':
                            $order_id = orderModel::query()->where('order_sn', $params['keywords'])->value('id');
                            $query    = $query->where('order_id', $order_id);
                            break;
                        case 'buyer_id':
                            $query = $query->where('buyer_id', $params['keywords']);
                            break;
                        case 'buyer_phone':
                            $buyer_id = memberModel::query()->where('phone', $params['keywords'])->value('id');
                            $query    = $query->where('buyer_id', $buyer_id);
                            break;
                        case 'goods_id':
                            $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_id', $params['keywords'])->pluck('id')->toArray());
                            break;
                        case 'goods_title':
                            $query = $query->whereIn('order_item_id', orderitemModel::query()->where('goods_title', 'like', "%{$params['keywords']}%")->pluck('id')->toArray());
                            break;
                    }
                }
            }
            if (isset($params['class']) && !empty($params['class'])) {
                $query = $query->where('class', $params['class']);
            }
            $total = $query->count();
            if (isset($params['sort'])) {
                $query = $query->orderBy($params['sort'] ?: 'id', (isset($params['order']) && in_array($params['order'], ['asc', 'desc'])) ? $params['order'] : 'desc');
            }
            $data = $query->offset(($page - 1) * $per_page)
                ->limit($per_page)
                ->get()->toArray();
            json([
                'total' => $total,
                'rows'  => $data
            ]);
        } else {
            $this->_view->display(strtolower($this->controller) . '/reward.html');
        }
    }
}
